package com.jinhongone.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author jinho
 * @className MutablePropertyValue
 * @description 存储和管理多个propertyValue对象, 实现迭代器支持迭代
 * @date 2025/4/25 15:40
 */
public class MutablePropertyValue implements Iterable<PropertyValue> {

    //知识点：final修改时变量需要在构造函数结束前赋值。
    private final List<PropertyValue> propertyValueList;

    public MutablePropertyValue() {
        propertyValueList = new ArrayList<>();
    }

    public MutablePropertyValue(List<PropertyValue> propertyValueList) {
        this.propertyValueList = propertyValueList != null ? propertyValueList : new ArrayList<>();
    }

    //获取全部propertyValues
    public PropertyValue[] getPropertyValues() {
        return propertyValueList.toArray(new PropertyValue[0]);
    }

    //根据属性名称获取属性对象
    public PropertyValue getPropertyValueByName(String name) {
        for (PropertyValue propertyValue : propertyValueList) {
            if (name.equals(propertyValue.getName())) return propertyValue;
        }
        return null;
    }

    //判断是否为空
    public boolean isEmpty() {
        return propertyValueList.isEmpty();
    }


    //添加propertyValue,返回值为自身，方便链式变成
    public MutablePropertyValue addPropertyValue(PropertyValue pv) {
        //判断是否已存在该元素，所存在进行替换，不存在新增
        for (int i = 0; i < propertyValueList.size(); i++) {
            if (propertyValueList.get(i).getName().equals(pv.getName())) {
                propertyValueList.set(i, pv); //set方法：将元素插入到特定下标
                return this; //方便链式编程
            }
        }
        propertyValueList.add(pv);
        return this;
    }

    //根据属性name判断是否已存在该属性对象
    public boolean contains(String propertyValueName) {
        //通过已有方法进行属性对象获取
        return getPropertyValueByName(propertyValueName) != null;
    }


    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.iterator();
    }
}
